import os
import time
from datetime import datetime, timezone, timedelta

from django.http import HttpResponse, StreamingHttpResponse
from django.shortcuts import render

from jenkins_ipa.settings import BASE_DIR


def file_iterator(file_path, chunk_size=50120):
    """
    文件生成器,防止文件过大，导致内存溢出
    :param file_path: 文件绝对路径
    :param chunk_size: 块大小
    :return: 生成器
    """
    with open(file_path, mode='rb') as f:
        while True:
            c = f.read(chunk_size)
            if c:
                yield c
            else:
                break


def getfiledir(path1):
    base_dir = os.path.dirname(BASE_DIR)
    file_dir = os.path.join(base_dir, path1, 'jenkins打包ipa')
    return file_dir


# Create your views here.
def slj(request):
    print("请求开始")
    # time.sleep(5)
    # for i in range(0, 100000000):
    #     a = 1 + i
    file_dir = getfiledir("英语四六级")
    res_list = []
    tz = timezone(timedelta(hours=+8))
    for root, dirs, files in os.walk(file_dir):
        files2 = [file for file in files if file.endswith(".ipa")]

        for res in files2:
            ab_file_path = os.path.getctime(os.path.join(root, res))
            ctime = datetime.fromtimestamp(ab_file_path, tz=tz)
            ctime_str = ctime.strftime('%Y-%m-%d %H:%M:%S')
            dic = {
                "ctime": ctime,
                "ctime_str": ctime_str,
                "pathdir": "slj",
                "filename": res
            }
            res_list.append(dic)
            print(ctime_str)
    res_list.sort(key=lambda dic: dic.get("ctime"), reverse=True)

    return render(request, "hello.html", {"title1": "英语四六级", "downloads": res_list})


# Create your views here.
def hello(request):
    print("请求开始")
    # time.sleep(5)
    # for i in range(0, 100000000):
    #     a = 1 + i
    file_dir = getfiledir("对啊课堂")
    res_list = []
    tz = timezone(timedelta(hours=+8))
    for root, dirs, files in os.walk(file_dir):
        files2 = [file for file in files if file.endswith(".ipa")]

        for res in files2:
            ab_file_path = os.path.getctime(os.path.join(root, res))
            ctime = datetime.fromtimestamp(ab_file_path, tz=tz)
            ctime_str = ctime.strftime('%Y-%m-%d %H:%M:%S')
            dic = {
                "ctime": ctime,
                "ctime_str": ctime_str,
                "pathdir": "duiaapp",
                "filename": res
            }
            res_list.append(dic)
            print(ctime_str)
    res_list.sort(key=lambda dic: dic.get("ctime"), reverse=True)

    return render(request, "hello.html", {"title1": "对啊课堂", "downloads": res_list})


# Create your views here.
def downslj(request, file_name):
    """
    下载压缩文件
    :param request:
    :param id: 数据库id
    :return:
    """
    ""
    file_path = os.path.join(getfiledir("英语四六级"), file_name)  # 下载文件的绝对路径

    if not os.path.isfile(file_path):  # 判断下载文件是否存在
        return HttpResponse("Sorry but Not Found the File")

    try:
        # 设置响应头
        # StreamingHttpResponse将文件内容进行流式传输，数据量大可以用这个方法
        response = StreamingHttpResponse(file_iterator(file_path))
        # 以流的形式下载文件,这样可以实现任意格式的文件下载
        response['Content-Type'] = 'application/octet-stream'
        # Content-Disposition就是当用户想把请求所得的内容存为一个文件的时候提供一个默认的文件名
        response['Content-Disposition'] = 'attachment;filename="{}"'.format(file_name)
    except Exception as e:
        return HttpResponse("Sorry but Not Found the File")

    return response

# Create your views here.
def downduia(request, file_name):
    """
    下载压缩文件
    :param request:
    :param id: 数据库id
    :return:
    """
    ""
    file_path = os.path.join(getfiledir("对啊课堂"), file_name)  # 下载文件的绝对路径

    if not os.path.isfile(file_path):  # 判断下载文件是否存在
        return HttpResponse("Sorry but Not Found the File")

    try:
        # 设置响应头
        # StreamingHttpResponse将文件内容进行流式传输，数据量大可以用这个方法
        response = StreamingHttpResponse(file_iterator(file_path))
        # 以流的形式下载文件,这样可以实现任意格式的文件下载
        response['Content-Type'] = 'application/octet-stream'
        # Content-Disposition就是当用户想把请求所得的内容存为一个文件的时候提供一个默认的文件名
        response['Content-Disposition'] = 'attachment;filename="{}"'.format(file_name)
    except Exception as e:
        return HttpResponse("Sorry but Not Found the File")

    return response
